//
//  HMSinaComposeViewController.swift
//  ZJCSina
//
//  Created by 朱建超 on 16/11/23.
//  Copyright © 2016年 itHeiMa. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMSinaComposeViewController: UIViewController {

    //按钮的监听事件
    func clicktabBarButton(button : UIButton) {
        
        switch button.tag {
        case 0:
            print("选择图片")
            //modal图片选择界面
            selectImageView.chooseImage(cell:nil)
        case 1:
            print("@某人")
        case 2:
            print("话题")
        case 3:
            print("选择表情")
            
            if !textView.isFirstResponder {
                textView.becomeFirstResponder()
            }
            
            //设置inputView ,完成键盘的切换
            if textView.inputView == nil {
                
                textView.inputView = keyboardView
                
            }else{
            
                textView.inputView = nil
            
            }
            //刷新输入视图
            textView.reloadInputViews()
            
        case 4:
            print("更多")
        default:
            print("")
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)

        //self.navigationItem.titleView初始值为nil,不能直接addSubView
        
        setNavigationBar()
        
        setTextView()
        
        if #available(iOS 9.0, *) {
            setToolBar()
        } else {
            // Fallback on earlier versions
        }
        
        //键盘通知的方法
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //表情键盘显示表情通知的方法
        NotificationCenter.default.addObserver(self, selector: #selector(selectEmotion(notification:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
        
        //设置图片选择器视图
        setSelectImageView()
        
        //将toolBar移到最顶层
        if #available(iOS 9.0, *) {
            self.view.bringSubview(toFront: toolBar)
        } else {
            // Fallback on earlier versions
        }
    }
    
    //当时图将要显示的时候，就应该判断是否显示图片选择器的视图
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if selectImageView.imageArray.count == 0 {
            selectImageView.view.isHidden = true
        }else{
            selectImageView.view.isHidden = false
        }
        
    }
    
    //实现键盘的通知方法
    func selectEmotion(notification : NSNotification) {
        
        print(notification)
        
        guard let emotion = notification.object as? HMEmoticon else{
        
            //返回的为空就代表点击的是删除按钮
            //执行回删的操作
            textView.deleteBackward()
            
            return
        
        }
        
        //如果点击的是emoji表情
        if emotion.type == 1 {
            
            //将emoji表情添加到对应的文本中
            textView.replace(textView.selectedTextRange!, withText: emotion.emojiStr ?? "")
            return
        }
        
//        //处理图片表情
        textView.inputEmoticon(em: emotion)
        
    }
    
    //键盘变化的通知
    @objc private func keyboardChanged(notification : NSNotification) {
        
        let endFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect

        //修改底部的约束,让底部的bottomTabBar能够移动
        let offSetY = -(UIScreen.main.bounds.height - endFrame.origin.y)
        //更新约束
        UIView.animate(withDuration: 0.25) {
            
            if #available(iOS 9.0, *) {
                self.toolBar.snp.updateConstraints({ (make) in
                    
                    make.bottom.equalTo(self.view.snp.bottom).offset(offSetY)
                    
                })
            } else {
                // Fallback on earlier versions
            }
            
            //强制刷新页面
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    func close() {
        
        dismiss(animated: true, completion: nil)
        
    }
    
    //发送按钮
    lazy var sendButton: UIBarButtonItem = {
        
        let sendButton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 40))
        //设置文字
        sendButton.setTitle("发送", for: .normal)
        //设置背景图片
        sendButton.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        sendButton.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        sendButton.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        //设置文字颜色
        sendButton.setTitleColor(UIColor.white, for: .normal)
        sendButton.setTitleColor(UIColor.darkGray, for: .disabled)
        
        //按钮的监听事件
        sendButton.addTarget(self, action: #selector(clickSendButton), for: .touchUpInside)
        
        let barButtonItem = UIBarButtonItem(customView: sendButton)
        barButtonItem.isEnabled = false
        
        return barButtonItem
    }()
    
    //发送按钮的点击事件
    @objc private func clickSendButton() {

        //https://api.weibo.com/2/statuses/update.json
        print("我被点击了")
        
        if selectImageView.imageArray.count == 0 {
            
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            let parameters = ["access_token" : HMSinaUserAccountViewModel.shared.access_token,
                              "status" : textView.imageEmoticon2Chs()] as [String : Any]
            
            HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
                
                if error != nil{
                    
                    SVProgressHUD.showError(withStatus: "发布微博失败")
                    
                    return
                    
                }
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
                
            }
            
        }else{  //发布微博图片的方法
        
            //https://upload.api.weibo.com/2/statuses/upload.json
            //图片微博
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let parameters = ["access_token" : HMSinaUserAccountViewModel.shared.access_token,
                              "status" : textView.imageEmoticon2Chs()] as [String : Any]
            
            let imageData = UIImagePNGRepresentation(selectImageView.imageArray.first!)
            
            HMNetworkTools.shared.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
                
                //将需要上传的文件的二进制数据拼接到formdata中
                /*
                 1、withFileData:需要上传的文件的二进制数据
                 2、name:服务器接收的字段 "pic"
                 3、fileName:服务器存储的名字
                 4、mimeType:标识文件类型
                 */
                formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "xxxxxx ", mimeType: "application/octet-stream")
                
            }, progress: nil, success: { (_, result) in
                SVProgressHUD.showSuccess(withStatus: "发布图片成功")
            }, failure: { (_, error) in
                SVProgressHUD.showError(withStatus: "发布图片失败")
            })
        
        }
        
        
    }
    
    //懒加载加载控件
    lazy var textView : HMEmoticonTextView = {
        
        let textView = HMEmoticonTextView()
        //添加占位文本
        
        
//        textView.text = "我是张三,我为自己代言"
        textView.font = UIFont.systemFont(ofSize: 17)
        textView.textColor = UIColor.darkGray
        //textView没有占位文本
        
        textView.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
        
        //为文本输入设置代理
        textView.delegate = self
        
        return textView
    }()
    
    //占位文本Label
    lazy var zhanWeiLabel: UILabel = {
        
        let zhanWeiText = UILabel(title: "我是张三,我为自己代言", font: 17, textColor: UIColor.lightGray)
        
    
        return zhanWeiText
    }()
    
    //懒加载底部工具条
    @available(iOS 9.0, *)
    lazy var toolBar: UIStackView = {
        
        let bottomBar = UIStackView()
        
        //设置方向
        bottomBar.axis = .horizontal
        //设置填充方法
        bottomBar.distribution = .fillEqually

        return bottomBar
    }()
    
    //懒加载自定义表情键盘
    lazy var keyboardView : HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
    
    //移除通知
    deinit {
        
        NotificationCenter.default.removeObserver(self)
        
    }
    
    //图片选择器的控制器
    lazy var selectImageView: HMSinaSelectImageController = {
        
        let flowLayout = UICollectionViewFlowLayout()
        let selectImageView = HMSinaSelectImageController(collectionViewLayout: flowLayout)
        
        flowLayout.itemSize = CGSize(width: selectImageWidth, height: selectImageWidth)
        flowLayout.minimumLineSpacing = itemJianJu
        flowLayout.minimumInteritemSpacing = itemJianJu
        flowLayout.sectionInset = UIEdgeInsets(top: itemJianJu, left: itemJianJu, bottom: 0, right: itemJianJu)
        
        return selectImageView
    }()

}

extension HMSinaComposeViewController : UITextViewDelegate{

    //textView的代理方法
    func textViewDidChange(_ textView: UITextView) {
        //判断发布微博按钮的状态
        sendButton.isEnabled = textView.hasText
        
        //占位文本要隐藏
        zhanWeiLabel.isHidden = textView.hasText
    }

}

//UI界面
extension HMSinaComposeViewController{
    
    //设置图片选择器
    func setSelectImageView() {
        
        //MARK:非常重要，添加子视图控制器
        self.addChildViewController(selectImageView)
        
        self.view.addSubview(selectImageView.view)
        
        //设置约束
        selectImageView.view.snp.makeConstraints { (make) in
            
            make.left.bottom.right.equalTo(self.view)
            make.top.equalTo(textView.snp.bottom)
            
        }
        
    }
    
    //搭建tabbar
    @available(iOS 9.0, *)
    func setToolBar() {
        
        self.view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp.makeConstraints { (make) in
            
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(44)
            
        }
        
        //添加按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        
        
        for (index ,imageName) in imageNames.enumerated() {
            
            let button = UIButton()
            
            button.setImage(UIImage(named : imageName), for: .normal)
            button.setImage(UIImage(named : imageName + "_highlighted"), for: .highlighted)
            //自适应大小
            button.sizeToFit()
            button.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
            //添加到tabbar
            toolBar.addArrangedSubview(button)
            
            //监听按钮的点击事件
            button.addTarget(self, action: #selector(clicktabBarButton(button:)), for: .touchUpInside)
            
            button.tag = index
            
        }
        
    }
    
    //设置textView
    func setTextView() {
        
        self.view.addSubview(textView)
        self.textView.addSubview(zhanWeiLabel)
        
        //实例化textView的控件
        textView.snp.makeConstraints { (make) in
        
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(UIScreen.main.bounds.height / 3  )
            
        }
        //设置占位文本的约束
        zhanWeiLabel.snp.makeConstraints { (make) in
            
            make.top.equalTo(self.textView.snp.top).offset(8)
            make.left.equalTo(self.textView.snp.left).offset(5)
            
            
        }
        
    }
    
    func setNavigationBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭" , target: self , action: #selector(close))
        
        //设置发布按钮
        self.navigationItem.rightBarButtonItem = sendButton
        
        //属性文本
        let titleLabel = UILabel()
        
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .center
        if let userName = HMSinaUserAccountViewModel.shared.userAccount?.name {
            
            let titleText = "发布微博\n\(userName)"
            titleLabel.text = titleText
            //修改属性文本的属性(用可变的)
            let text = NSMutableAttributedString(string: titleText )
            //获取用户名的范围
            let range = (titleText as NSString).range(of: userName)
            //给用户名添加属性
            text.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 13) , NSForegroundColorAttributeName : UIColor.darkGray], range: range)
            
            //给label的属性文本赋值
            titleLabel.attributedText = text
            
        }else{
            
            titleLabel.text = "发布微博"
            
        }
        
        titleLabel.sizeToFit()
        
        self.navigationItem.titleView = titleLabel
        
    }

}
